package com.rgs.se.concurrent.lock;

import org.I0Itec.zkclient.ZkClient;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Ren Gaoshuai
 * @ClassName LocksZookeeper
 * @Description zookeeper 实现分布式锁 获取唯一id
 * @date 2021-10-27 11:45
 **/
public class LocksZookeeper {

    private static String lock = "/lock";
    private static ZkClient client;
    private static int num = 0;
    private static ExecutorService executorService = Executors.newFixedThreadPool(2);
    private static String CONNECTION = "127.0.0.1:2181";

    static {
        client = new ZkClient(CONNECTION);
        LocksZookeeper.unLock();
    }

    /**
     * 加锁
     */
    public static void lock(){
        try {
            client.createEphemeral(lock);
        } catch (Exception e) {
            try {
                System.out.println("重新加锁。。。");
                Thread.sleep(10);
                lock();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }

    }

    /**
     * 解锁
     */
    public static void unLock(){
        client.delete(lock);
    }
    /**
     * 获取当前时间字符串
     * 高并发情况下不能保证唯一，后面需要拼接编号
     * @return
     */
    public static String getStringDateFormat(){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        return dtf.format(now);
    }


    public static void main(String[] args) {
        //线程1
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    LocksZookeeper.lock();
                    num++;
                    System.out.println(Thread.currentThread().getName() + " "  + getStringDateFormat() + " "+ num);
                    LocksZookeeper.unLock();
                }
            }
        });

        //线程2
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    LocksZookeeper.lock();
                    num++;
                    System.out.println(Thread.currentThread().getName() + " "  + getStringDateFormat() + " "+ num);
                    LocksZookeeper.unLock();
                }
            }
        });

        /**
         * 以上就是模拟两个线程去获取id
         */

        executorService.shutdown();
        try {
            executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}